package com.sanjiahantang.youjiarole.module.common.presenters;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;

import com.sanjiahantang.uilibrary.R;
import com.sanjiahantang.uilibrary.adapter.listview.BaseAdapterHelper;
import com.sanjiahantang.uilibrary.adapter.listview.QuickAdapter;
import com.sanjiahantang.uilibrary.utils.Utils;
import com.sanjiahantang.youjiarole.base.BaseMvpActivity;
import com.sanjiahantang.youjiarole.base.BaseMvpPresenter;
import com.sanjiahantang.youjiarole.base.BaseView;
import com.sanjiahantang.youjiarole.base.CallBack;
import com.sanjiahantang.youjiarole.config.ConfigValue;
import com.sanjiahantang.youjiarole.config.SPConfig;
import com.sanjiahantang.youjiarole.module.common.beans.MeIcon;
import com.sanjiahantang.youjiarole.module.common.beans.MessageNoticeCountBean;
import com.sanjiahantang.youjiarole.module.common.beans.PersonBean;
import com.sanjiahantang.youjiarole.module.common.models.IUserModel;
import com.sanjiahantang.youjiarole.module.common.models.impl.UserModel;
import com.sanjiahantang.youjiarole.module.common.views.MeView;
import com.sanjiahantang.youjiarole.module.common.views.impl.MeAccountActivity;
import com.sanjiahantang.youjiarole.module.common.views.impl.MessageActivity;
import com.sanjiahantang.youjiarole.module.common.views.impl.MyCoustomerActivity;
import com.sanjiahantang.youjiarole.module.common.views.impl.MyProjectpartnerActivity;
import com.sanjiahantang.youjiarole.module.common.views.impl.SettingsActivity;
import com.sanjiahantang.youjiarole.module.complain.views.impl.MeComplainActivity;
import com.sanjiahantang.youjiarole.module.decorate.views.impl.DecorateDetailActivity;
import com.sanjiahantang.youjiarole.module.evaluate.views.impl.MeEvaluateActivity;
import com.sanjiahantang.youjiarole.module.login.views.impl.LoginActivity;
import com.sanjiahantang.youjiarole.module.login.views.impl.RegisterActivity;
import com.sanjiahantang.youjiarole.module.me.contract.views.impl.ContractActivity;
import com.sanjiahantang.youjiarole.module.me.favorite.views.impl.FavoriteActivity;
import com.sanjiahantang.youjiarole.module.me.order.views.impl.MyOrderActivity;
import com.sanjiahantang.youjiarole.module.me.scheme.views.impl.MeSchemeListActivity;
import com.sanjiahantang.youjiarole.utils.SPUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import q.rorbin.badgeview.QBadgeView;

import static com.sanjiahantang.youjiarole.utils.SPUtils.get;

/**
 * Created by zy on 2017/9/4.
 */

public class MePresenter extends BaseMvpPresenter<MeView> implements CallBack<PersonBean> {
    private QuickAdapter<MeIcon> mQuickAdapter;

    private MeIcon miBean;
    private String[] items = {"待付款", "部分付款", "已付款", "已完成"};
    private int[] icons = {R.drawable.i_wait_payment, R.drawable.i_wait_deliver,
            R.drawable.i_wait_receive, R.drawable.i_after_sale};
    private IUserModel userModel;

    public MePresenter(){
        userModel = new UserModel();
    }

    public QuickAdapter<MeIcon> initGridAdapter(BaseMvpActivity context){
        ArrayList<MeIcon> list = new ArrayList<>();
        for (int i = 0; i < items.length; i++) {
            miBean = new MeIcon();
            miBean.setItems(items[i]);
            miBean.setIcon(icons[i]);
            list.add(miBean);
        }

        mQuickAdapter = new QuickAdapter<MeIcon>(context, R.layout.item_me_icon) {
            @Override
            protected void convert(BaseAdapterHelper helper, MeIcon item) {
                helper.getView(R.id.imgIcon).setBackgroundResource(item.getIcon());
                helper.setText(R.id.txtItem, item.getItems());
                ImageView orderType = helper.getView(R.id.imgIcon);
                if (!TextUtils.isEmpty(item.getNum()) && !item.getNum().equals("null") && Integer.valueOf(item.getNum())!=0){
                    new QBadgeView(context).bindTarget(orderType).setBadgeGravity(Gravity.TOP | Gravity.END)
                            .setBadgeNumber(Integer.valueOf(item.getNum()))
                            .setGravityOffset(-2,-2, true)
                            .setBadgeTextSize(8, true);
                }
            }
        };

        mQuickAdapter.addAll(list);
        return mQuickAdapter;
    }




    public boolean network(final BaseMvpActivity activity) {
        if (Utils.NO_NETWORK_STATE == Utils.isNetworkAvailable(activity)) {
            Utils.showDialog(activity, "提示", "您现在的网络不是太好哦！", "", "重试", new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    switch (view.getId()) {
                        case R.id.txtDialogCancel:
                            Utils.dismissDialog();
                            break;
                        case R.id.txtDialogSure:
                            Utils.dismissDialog();
                            initUserData(activity);
                            break;
                    }
                }
            });
            return false;
        }
        return true;
    }

    public void toLogin(BaseMvpActivity context) {
        LoginActivity.logout(context);
    }
    public void toMePartner(BaseMvpActivity context) {
        if(checkLogin(context)){
            Intent itLogin = new Intent(context, MyProjectpartnerActivity.class);
            context.startActivity(itLogin);
        }

    }
    public void toMeAccount(BaseMvpActivity context) {
        if (checkLogin(context)){
            Intent meAccount = new Intent(context, MeAccountActivity.class);
            context.startActivity(meAccount);
        }

    }
    private void initUserData(BaseMvpActivity context) {
        ConfigValue.DATA_KEY = (String) get(context, SPConfig.KEY, "");
        if (!TextUtils.isEmpty(ConfigValue.DATA_KEY)) {
            Map<String,String> params = new HashMap<>();
            params.put(KEY_TOKEN, ConfigValue.DATA_KEY);
            params.put(KEY_ROLE_ID, ""+SPUtils.get(context,SPConfig.ROLE_ID,""));
            params.put(KEY_PHONE,SPUtils.get(context,SPConfig.PHONE,"").toString());
            mView.showProgress();
            userModel.loadUserInfo(context,params,this);
        } else {
            mView.changeUIToLogout();
        }
    }

    private QuickAdapter<MeIcon> initGrid(BaseMvpActivity context) {
        ArrayList<MeIcon> list = new ArrayList<>();
        for (int i = 0; i < items.length; i++) {
            miBean = new MeIcon();
            miBean.setItems(items[i]);
            miBean.setIcon(icons[i]);
            list.add(miBean);
        }


        mQuickAdapter= new QuickAdapter<MeIcon>(context, R.layout.item_me_icon) {
            @Override
            protected void convert(BaseAdapterHelper helper, MeIcon item) {
                helper.getView(R.id.imgIcon).setBackgroundResource(item.getIcon());
                helper.setText(R.id.txtItem, item.getItems());
                ImageView orderType = helper.getView(R.id.imgIcon);
                if (!TextUtils.isEmpty(item.getNum()) && !item.getNum().equals("null") && Integer.valueOf(item.getNum())!=0){
                    new QBadgeView(context).bindTarget(orderType).setBadgeGravity(Gravity.TOP | Gravity.END)
                            .setBadgeNumber(Integer.valueOf(item.getNum()))
                            .setGravityOffset(-2,-2, true)
                            .setBadgeTextSize(8, true);
                }

            }
        };
        mQuickAdapter.addAll(list);
        return mQuickAdapter;
    }




    public void onItemClick(BaseMvpActivity context, int type1, int type2) {
        if (network(context)) {
            if (!TextUtils.isEmpty(ConfigValue.DATA_KEY)) {
                Intent intent = new Intent(context,MyOrderActivity.class);
                intent.putExtra("type1",type1);
                intent.putExtra("type2",type2);
                context.startActivity(intent);
            } else {
                toLogin(context);
            }
        }
    }

    private void goPageCheckNet(BaseMvpActivity context,Class toPage){
        if (network(context)) {
            goPageSimply(context,toPage);
        }
    }

    private void goPageCheckNetAndLogin(BaseMvpActivity context,Class toPage){
        if (network(context)) {
            if (!TextUtils.isEmpty(ConfigValue.DATA_KEY)) {
                goPageSimply(context,toPage);
            } else{
                toLogin(context);
            }
        }
    }

    public void goMessagePage(BaseMvpActivity context) {
        if (checkLogin(context)){
            goPageSimply(context,MessageActivity.class);
        }

    }

    private boolean checkLogin(Context context){
        if (!TextUtils.isEmpty(ConfigValue.DATA_KEY)){
            return true;
        }else {
            context.startActivity(new Intent(context,LoginActivity.class));
            return false;
        }
    }


    public void goRegisterPage(BaseMvpActivity context) {
        goPageSimply(context,RegisterActivity.class);
    }

    public void goDecorateManagerPage(BaseMvpActivity context) {
        if (checkLogin(context))
        goPageCheckNetAndLogin(context,DecorateDetailActivity.class);
    }

    public void goCustomer(BaseMvpActivity context) {
        if (checkLogin(context)) {

            Intent intent = new Intent(context, MyCoustomerActivity.class);
            context.startActivity(intent);
        }
    }

    public void goSchemePage(BaseMvpActivity context) {
        if (checkLogin(context))
        goPageCheckNetAndLogin(context, MeSchemeListActivity.class);
    }

    public void goAllOrderPage(BaseMvpActivity context) {
        if (checkLogin(context))
        goPageCheckNetAndLogin(context,MyOrderActivity.class);
    }

    public void goFavoritePage(BaseMvpActivity context) {
        if (checkLogin(context))
        goPageCheckNetAndLogin(context,FavoriteActivity.class);
    }

    public void goContractPage(BaseMvpActivity context) {
        if (checkLogin(context))
        goPageSimply(context,ContractActivity.class);
    }


    /**
     * 我的评价
     * @param context
     */
    public void goEvaluatePage(BaseMvpActivity context) {
        if (checkLogin(context))
        goPageSimply(context,MeEvaluateActivity.class);
    }

    public void goSettingsPage(BaseMvpActivity context) {
        if (checkLogin(context))
        goPageSimply(context,SettingsActivity.class);
    }




    public void goCSDPage(BaseMvpActivity context) {
        if (checkLogin(context))
        goPageCheckNetAndLogin(context,MeComplainActivity.class);
    }

    private void showInfo(Context context) {
        mView.changeUIToLogin();
        ArrayList<MeIcon> list = new ArrayList<>();
        for (int i = 0; i < items.length; i++) {
            miBean = new MeIcon();
            miBean.setItems(items[i]);
            miBean.setIcon(icons[i]);
            list.add(miBean);
        }

        if(mQuickAdapter == null){
            mQuickAdapter= new QuickAdapter<MeIcon>(context, R.layout.item_me_icon) {
                @Override
                protected void convert(BaseAdapterHelper helper, MeIcon item) {
                    helper.getView(R.id.imgIcon).setBackgroundResource(item.getIcon());
                    helper.setText(R.id.txtItem, item.getItems());
                    ImageView orderType = helper.getView(R.id.imgIcon);



                    if (!TextUtils.isEmpty(item.getNum()) && !item.getNum().equals("null") && Integer.valueOf(item.getNum())!=0){
                        new QBadgeView(context).bindTarget(orderType).setBadgeGravity(Gravity.TOP | Gravity.END)
                                .setBadgeNumber(Integer.valueOf(item.getNum()))
                                .setGravityOffset(-2,-2, true)
                                .setBadgeTextSize(8, true);
                    }

                }
            };
        }
        mQuickAdapter.clear();
        mQuickAdapter.addAll(list);
        mView.reloadGridAdapter(mQuickAdapter);
    }

    @Override
    public void onSuccess(PersonBean response, Context context, Object tag) {
        if (mView == null) return;
        mView.hideProgress();
        String message = response.getMessage();
        if (response.getCode() == RESPONSE_CODE_SUC) {
            ConfigValue.userInfo = response.getData();
            if (response.getData().getUserName() != null) {
                SPUtils.put(context, SPConfig.USERNAME, response.getData().getUserName());
            }
            if (response.getData().getAddress() != null) {
                SPUtils.put(context, SPConfig.ADDRESS, response.getData().getAddress());
                String[] addressArr = response.getData().getAddress().split(" ");
            }
            if (response.getData().getSysPoints() != null) {
                SPUtils.put(context, SPConfig.SYS_SPOINTS, response.getData().getSysPoints());
            }

            if (ConfigValue.userInfo != null && !TextUtils.isEmpty(ConfigValue.userInfo.getQrCode())){
                SPUtils.put(context,SPConfig.QR_CODE,ConfigValue.userInfo.getQrCode());
            }

            if (response.getData().getSignTime() != null) {
                String time = response.getData().getSignTime();
                long year = 1;
                try {
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
                    Date date = df.parse(time);
                    year = yearDateDiff(date);
                    Log.e("year","" + year);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                SPUtils.put(context, SPConfig.SIGN_TIME, "签约" + year + "年");
            }

            showInfo(context);
            return;

        }else{
            SPUtils.remove(context, SPConfig.KEY);
            Utils.showToast(context, message);
        }

    }

    //计算两个日期相差年数
    private static int yearDateDiff(Date startDate){
        Calendar calBegin = Calendar.getInstance(); //获取日历实例
        Calendar calEnd = Calendar.getInstance();
        calBegin.setTime(startDate); //字符串按照指定格式转化为日期
        calEnd.setTime(new Date(System.currentTimeMillis()));
        return calEnd.get(Calendar.YEAR) - calBegin.get(Calendar.YEAR) > 0 ? (calEnd.get(Calendar.YEAR) - calBegin.get(Calendar.YEAR) + 1) : 1;
    }

    @Override
    public void onFailure(String message) {
        if (mView == null) return;
        mView.hideProgress();
    }

    public void onLoad(BaseMvpActivity context) {
        if(TextUtils.isEmpty(ConfigValue.DATA_KEY)){
            if (mView == null) return;
            mView.changeUIToLogout();
        }else if(ConfigValue.userInfo == null){
            initUserData(context);
        }else{
            showInfo(context);
        }
    }

    public void getSearchNoticeCountForCustomer(Context context, final BaseView.OnLoadListener listener) {
        Map<String,String> map=new HashMap<>();
        String roleId= SPUtils.get(context, SPConfig.ROLE_ID,"").toString();
        map.put("roleId",roleId);
        map.put("rolePhone",SPUtils.get(context,SPConfig.PHONE,"").toString());
        map.put(KEY_TOKEN,ConfigValue.DATA_KEY);
        userModel.getSearchNoticeCountForCustomer(context,map,new CallBack<MessageNoticeCountBean>() {
            @Override
            public void onSuccess(MessageNoticeCountBean response, Context context, Object tag) {
                if (response != null && response.getCode() == RESPONSE_CODE_SUC
                        && response.getListData() != null && response.getListData().size() > 0){
                    listener.onLoad(response.getListData().get(0).getNum());
                }else{
                    listener.onLoad(null);
                }
            }

            @Override
            public void onFailure(String message) {
                listener.onLoad(null);
            }
        });
    }
}
